package com.lenovo.newsapp.share;

import com.lenovo.newsapp.util.ThreadPool;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;


public class ShareToTwitter {
	private static final String TAG = "ShareToTwitter";
	
	public static final String PREF_ACCESS_TOKEN = "accessToken";
	public static final String PREF_ACCESS_TOKEN_SECRET = "accessTokenSecret";

	private static final String CONSUMER_KEY = "6XoyMbwZ6mXckaXfZS5xg";
	private static final String CONSUMER_SECRET = "JBjQ4onLeFTmINdxvj3X7CUk9OnxB7NqRBZMUZoE"; // XXX
	private static final String CALLBACK_URL = "https://lenovocentral.lenovo.com";
	private SharedPreferences mPrefs;
	private Twitter mTwitter;
	private RequestToken mReqToken;

	private Button mLoginButton;
	private Button mTweetButton;
	final Handler handler = new Handler();
	private WebView web;
	private EditText et;

	private String title;

	private ProgressBar webpd;
	private boolean success;
	
	public void sendTwitter(final String str) {
		Log.v(TAG, str);
		final String token = mPrefs.getString(PREF_ACCESS_TOKEN, null);
		final String secret = mPrefs.getString(PREF_ACCESS_TOKEN_SECRET, null);
		if (token == null && secret == null) {
			loginNewUser();
			return;
		}
//		webpd.setVisibility(View.VISIBLE);
		ThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				try {

					AccessToken at = new AccessToken(token, secret);

					mTwitter.setOAuthAccessToken(at);
					Log.i(TAG, "开始发送文字---");

					Status status = mTwitter.updateStatus(str.toString());
					Log.i(TAG, "完成---" + status.getText());

						success = true;
				} catch (TwitterException e) {
					success = false;
					Log.i(TAG, "异常---" + e);
					e.printStackTrace();
				}
				handler.post(new Runnable() {

					@Override
					public void run() {

//						webpd.setVisibility(View.GONE);
						if (success) {
//							Toast.makeText(TweetToTwitterActivity.this, "success",
//									Toast.LENGTH_LONG).show();
						} else {
//							Toast.makeText(TweetToTwitterActivity.this, "failed",
//									Toast.LENGTH_LONG).show();
						}

//						finish();
					}

				});
			}
		});
	}

	/**
	 * 授权
	 */

	private void loginNewUser() {
//		webpd.setVisibility(View.VISIBLE);
		ThreadPool.execute(new Runnable() {

			@Override
			public void run() {

				try {
					Log.i(TAG, "Request App Authentication");

					mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);

					success = true;
					

				} catch (TwitterException e) {
					Log.i(TAG, "e---" + e);
					success = false;
				}

				handler.post(new Runnable() {

					@Override
					public void run() {
						
						Log.i(TAG, "Starting Webview to login to twitter");
						if(success){
						if(mReqToken != null ){
							String url = mReqToken.getAuthenticationURL();
							
							Log.i(TAG, "url--" + url);
//							webpd.setVisibility(View.GONE);
//							et.setVisibility(View.GONE);
//							mTweetButton.setVisibility(View.GONE);
							if(url == null){
//								Toast.makeText(TweetToTwitterActivity.this, "failed",
//										Toast.LENGTH_LONG).show();
//								finish();
							}else{
								
								goShowWeb(url);
							}
						}else{
//							Toast.makeText(TweetToTwitterActivity.this, "failed",
//									Toast.LENGTH_LONG).show();
//							finish();
						}
						}else{
//							Toast.makeText(TweetToTwitterActivity.this, "failed",
//									Toast.LENGTH_LONG).show();
//							finish();
						}
						

					}

				});
			}
		});

	}

	/**
	 * 展示授权页面
	 */
	private void goShowWeb(String url) {

		web.setVisibility(View.VISIBLE);
		web.loadUrl(url);
		web.setWebViewClient(new WebViewClient() {
			private String oauthToken;
			private String oauthVerifier;

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				if (url != null && url.startsWith(CALLBACK_URL)) {
					web.setVisibility(View.GONE);
					String[] param = url.split("\\?")[1].split("&");
					if (param[0].startsWith("oauth_token")) {
						oauthToken = param[0].split("=")[1];
					} else if (param[1].startsWith("oauth_token")) {
						oauthToken = param[1].split("=")[1];
					}
					if (param[0].startsWith("oauth_verifier")) {
						oauthVerifier = param[0].split("=")[1];
					} else if (param[1].startsWith("oauth_verifier")) {
						oauthVerifier = param[1].split("=")[1];
					}
					Log.i(TAG, "oauthVerifier--" + oauthVerifier);
					authoriseNewUser(oauthVerifier);
				}
				;
			}
		});
	}

//	@Override
//	protected void onNewIntent(Intent intent) {
//		super.onNewIntent(intent);
//		Log.i(TAG, "New Intent Arrived");
//	}
//
//	@Override
//	protected void onResume() {
//		super.onResume();
//		Log.i(TAG, "Arrived at onResume");
//	}

	/**
	 * 获取AccessToken
	 * 
	 * @param oauthVerifier
	 */
	private void authoriseNewUser(final String oauthVerifier) {
		Log.i(TAG, "开始获取accesstoken--");
		webpd.setVisibility(View.VISIBLE);
		ThreadPool.execute(new Runnable() {

			private AccessToken at;

			@Override
			public void run() {

				try {
					at = mTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
					long id = at.getUserId();
					Log.i(TAG, "userid--" + id);
					String token = at.getToken();
					String secret = at.getTokenSecret();
					Log.i(TAG, "token---" + token);
					Log.i(TAG, "secret---" + secret);
					Editor editor = mPrefs.edit();
					editor.putString(PREF_ACCESS_TOKEN, token);
					editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
					editor.commit();
					Status status = mTwitter.updateStatus(et.getText()
							.toString());
					Log.i(TAG, "授权后直接发送---" + status.getText());
//					saveAccessToken(at);
						success = true;
				} catch (TwitterException e) {
					Log.i(TAG, "e---" + e);
					success = false;
					e.printStackTrace();
				}
				handler.post(new Runnable() {

					@Override
					public void run() {
						webpd.setVisibility(View.VISIBLE);
						Log.i(TAG, "授权后success---" + success);
						if (success) {
//							Toast.makeText(TweetToTwitterActivity.this, "success",
//									Toast.LENGTH_LONG).show();
						} else {
//							Toast.makeText(TweetToTwitterActivity.this, "sent",
//									Toast.LENGTH_LONG).show();
						}
//						finish();
					}
				});
			}
		});

	}

	/**
	 * 存储AccessToken
	 * 
	 * @param at
	 */
	private void saveAccessToken(AccessToken at) {
		String token = at.getToken();
		String secret = at.getTokenSecret();
		Log.i(TAG, "token---" + token);
		Log.i(TAG, "secret---" + secret);
		Editor editor = mPrefs.edit();
		editor.putString(PREF_ACCESS_TOKEN, token);
		editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
		editor.commit();
	}

//	public void sendTwitter() {
//		// TODO Auto-generated method stub
//		
//	}
}
